import aiortc
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.media import MediaPlayer, MediaRelay, MediaRecorder
from aiortc.rtcrtpsender import RTCRtpSender

import aiohttp
from aiohttp import TCPConnector
import asyncio
import random
import json
import time
import ssl

ip = "39.106.77.250"
stream_url = "webrtc://{}:1990/live/livestream1?schema=https".format(ip)
api = "https://{}:1990/rtc/v1/play/".format(ip)

print("Stream URL:", stream_url)
print("API URL:", api)

async def main():
    print("Starting main function")
    
    recorder = MediaRecorder("output.mp4")    
    
    print("Creating RTCPeerConnection")
    pc = RTCPeerConnection()
    
    @pc.on("connectionstatechange")
    async def on_connectionstatechange():
        print("Connection state:", pc.connectionState)
        if pc.connectionState == "failed":
            await pc.close()
            
    @pc.on("track")
    def on_track(track):
        print("Track received:", track)
        recorder.addTrack(track)


    pc.addTransceiver("video", direction="recvonly")
    offer = await pc.createOffer()
    await pc.setLocalDescription(offer)
    
    global stream_url, api
    print("URL: ", stream_url)
    data = {
        "api": api,
        "tid": hex(int(time.time()) * random.randint(8932891839, 312371231928731))[2:9],
        "streamurl": stream_url,
        "clentip": None,
        "sdp": offer.sdp
    }
    
    print("Sending POST request to API")
    print(data)
    response = None
    async with aiohttp.ClientSession() as session:
        async with session.post(api, data=json.dumps(data), ssl=False) as resp:
            response = await resp.json()
    
    print("Response received:", response)
    
    await pc.setRemoteDescription(RTCSessionDescription(
        sdp=response["sdp"], type="answer"
    ))
    await recorder.start()
    
    await asyncio.sleep(10000)
    
    
if __name__ == "__main__":
    print("Running main function")
    asyncio.run(main())